package com.example.cor.chain;

import com.example.cor.filter.Filter;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;

public class ApplicationFilterChain implements FilterChain{

    private static int INCREMENT = 10;

    private Filter[] filters = new Filter[0];

    // filter count
    private int count;

    @Override
    public void addFilter(Filter filter) {
        for (Filter f : filters) {
            if (filter == f) {
                return;
            }
        }
        if (count == filters.length) {
            // no capacity
            Filter[] newFilters = new Filter[count + INCREMENT];
            System.arraycopy(filters,0,newFilters,0,count);
            this.filters = newFilters;
        }

        filters[count++] = filter;
    }

    // target
    private Servlet servlet;


    @Override
    public void setTarget(Servlet servlet) {
        this.servlet = servlet;
    }

    // current next filter
    private int idx;


    @Override
    public void next(ServletRequest request, ServletResponse response) throws IOException, ServletException {
        if (idx < count) {
            Filter filter = filters[idx++];
            filter.interceptor(request,response,this);
            return;
        }
        // call target
        servlet.service(request,response);
    }
}
